﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.Linq;

namespace MyDHServer.DataAccess
{
    public static class DataBaseHelper
    {
        public const string ConnectionStringName = "MyDHServerConn";

        public static MyDHServerDataContext GetDataContext()
        {
            var db = new MyDHServerDataContext(ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString);
            return db;
        }

        public static void Update<T>(T obj, Action<T> update) where T:class
        {
            var db = GetDataContext();
            db.GetTable<T>().Attach(obj);
            update(obj);
            db.SubmitChanges();
        }

        public static void UpdateAll<T>(List<T> items, Action<T> update) where T : class
        {
            var db = GetDataContext();

            foreach (T item in items)
            {
                db.GetTable<T>().Attach(item);
                update(item);
            }
            db.SubmitChanges();
        }

        public static void Delete<T>(Action<T> makTemplate) 
            where T : class,new()

        {
            var db = GetDataContext();
            T template = new T();
            makTemplate(template);
            db.GetTable<T>().Remove(template);
            db.SubmitChanges();
        }

        public static void Insert<T>(T obj)where T:class
        {
            var db = GetDataContext();
            db.GetTable<T>().Add(obj);
            db.SubmitChanges();
        }
    

    }
}
